package com.sinotrans.common.aop;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

public class AopUtil {

	/**
	 * 获取被切面的类
	 * 
	 * @param pjp
	 * @return
	 */
	public static Class<?> pointClass(JoinPoint pjp) {
		return pjp.getTarget().getClass();
	}

	/**
	 * 获取被切面的方法
	 * 
	 * @param pjp
	 * @return
	 * @throws Exception
	 */
	public static Method pointMethod(JoinPoint pjp) throws Exception {
		Method result = null;
		Class<?> targetClass = pjp.getTarget().getClass();
		Signature signature = pjp.getSignature();
		if (signature instanceof MethodSignature) {
			MethodSignature methodSignature = (MethodSignature) signature;
			Class<?>[] paramTypes = methodSignature.getParameterTypes();
			String methodName = pjp.getSignature().getName();
			result = targetClass.getMethod(methodName, paramTypes);
		}
		return result;
	}

	/**
	 * 获取被切面类的注解
	 * 
	 * @param pjp
	 * @return
	 * @throws Exception
	 */
	public static Annotation[] pointClassAnnotation(JoinPoint pjp) {
		return pjp.getTarget().getClass().getAnnotations();
	}

	/**
	 * 获取被切面方法的注解
	 * 
	 * @param pjp
	 * @return
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws Exception
	 */
	public static Annotation[] pointMethodAnnotation(JoinPoint pjp) throws Exception {
		Method targetMethod = pointMethod(pjp);
		return targetMethod.getAnnotations();
	}

	/**
	 * 是否包含{@link org.springframework.stereotype.Controller}注解
	 * 
	 * @param annotations
	 * @return
	 */
	public static boolean isController(Annotation[] annotations) {
		boolean is = false;
		for (int i = 0; i < annotations.length; ++i) {
			Annotation annotation = annotations[i];
			if (annotation instanceof Controller || annotation instanceof RestController) {
				is = true;
				break;
			}
		}
		return is;
	}

}
